import 'dart:ui';

import 'package:flutter/cupertino.dart';

extension StringExt on String {
  Color toColor() {
    final buffer = StringBuffer();
    if (length == 6 || length == 7) buffer.write('ff');
    buffer.write(replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  static String toCharacterBreakStr(String word) {
    if (word.isEmpty) {
      return word;
    }
    String breakWord = '';
    word.runes.forEach((element) {
      breakWord += String.fromCharCode(element);
      breakWord += '\u200B';
    });
    return breakWord;
  }

  String price({position = 3}) {
    var priceDouble = double.tryParse(this);
    // 处理 E-数字 类型
    if (priceDouble == 0.0) return '0.0000';
    // print("price:: $this $priceDouble ");
    if (priceDouble! < 0.00001) {
      // 0.000003456  {6}  3 + 2 + 1
      int zeroCount = int.parse(priceDouble.toString().split('e-')[1]) - 1;
      String prefix = "0.{$zeroCount}";
      String newStr =
          priceDouble.toString().replaceAll(".", "").replaceAll("e-", "");
      String end = newStr.substring(0, newStr.length <= 3 ? newStr.length : 3);
      return prefix + end;
    }
    if (priceDouble! > 1000000) {
      return "${(priceDouble / 1000000.0).toStringAsFixed(3)}M";
    }
    if (priceDouble > 1000) {
      return "${(priceDouble / 1000.0).toStringAsFixed(3)}K";
    }
    return priceDouble.toStringAsFixed(position);
  }

  String amount() {
    // debugPrint("================>$this");
    var position = 3;
    var amountDouble = double.parse(this);
    if (amountDouble == 0.0) return '0.0000';
    if (amountDouble > 1000000) {
      return "${(amountDouble / 1000000.0).toStringAsFixed(position)}M";
    } else if (amountDouble > 1000) {
      return "${(amountDouble / 1000.0).toStringAsFixed(position)}K";
    }
    return amountDouble.toStringAsFixed(position);
  }

  // ['yyyy', '年', 'mm', '月', 'dd']
  // String time(List<String> formats) {
  //   // var time = "${datetime.hour}:${datetime.minute}:${datetime.second}";
  //   // formatDate(datetime, ['yyyy', '年', 'mm', '月', 'dd']);
  //   return dateFormat(
  //       DateTime.fromMillisecondsSinceEpoch(int.parse(this) * 1000), formats);
  //   // return DateTime.fromMillisecondsSinceEpoch(int.parse(this) * 1000)
  //   //     .minute
  //   //     .toString();
  // }

  datetime() {}

  String address() {
    if (length > 8) {
      // 保留8位, 前面5位, 后面三位
      String head = substring(0, 4);
      String tail = substring(length - 3, length);
      return "$head...$tail";
    }
    return this;
  }
}
